﻿using BootstrapAdmin.DataAccess.Models;
using BootstrapAdmin.DataAccess.Models.Production;
using BootstrapAdmin.Web.Core.Models;
using BootstrapAdmin.Web.Core.Services;
using PetaPoco;

namespace BootstrapAdmin.DataAccess.PetaPoco.Services;

internal sealed class InboundService : IInboundService
{
    private readonly IDBManager _dbManager;

    public InboundService(IDBManager db) => _dbManager = db;

    public async Task<ApiResult> SaveInboundAsync(ApiData data)
    {
        var sn = data.GetValue<string>("PLC_Inbound_SN");
        var formula = data.GetValue<int>("PLC_Inbound_Formula");
        var pallet = data.GetValue<string>("PLC_Inbound_Pallet");
        if (string.IsNullOrWhiteSpace(sn))
        {
            return ApiResult.Error(ErrorCode.ErrEmptyOfSN);
        }
        if (formula == 0)
        {
            return ApiResult.Error(ErrorCode.ErrEmptyOfFormula);
        }

        InboundInfo inboundEntity = new()
        {
            Station = data.Schema.Station,
            Formula = formula,
            ProductCode = "", // 配方与产品不是一一对应关系
            SN = sn,
            Pallet = pallet,
            CreatedAt = DateTime.Now,
        };

        // 记录进站信息
        using var db = _dbManager.Create();

        try
        {
            db.BeginTransaction();

            await db.InsertAsync(inboundEntity);

            // 记录当前工站生产的产品信息
            Sql sql = new();
            sql.Where("Station = @0", data.Schema.Station);
            var prodStation = await db.FirstOrDefaultAsync<ProductionStation>(sql);
            if (prodStation == null)
            {
                prodStation = new()
                {
                    Station = data.Schema.Station,
                    CurrentOrderNo = "",
                    CurrentSN = sn
                };
                await db.SaveAsync(prodStation);
            }
            else
            {
                await db.UpdateAsync<ProductionStation>("SET CurrentSN = @0 WHERE Id = @1", sn, prodStation.Id);
            }

            db.CompleteTransaction();
        }
        catch (Exception ex)
        {
            db.AbortTransaction();
            return ApiResult.Error(ex.Message);
        }

        return ApiResult.Ok();
    }
}
